package DaoImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import Dao.FinanceDAO;
import Entity.Activity;
import Entity.Finance;
import Entity.Stlist;
import Util.HibernateUtil;

public class FinanceDaoImpl implements FinanceDAO {

	//添加一条记录
	@Override
	public boolean addFinance(Finance finance, String stid) {
		Transaction ts = null;
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			ts = session.beginTransaction();
		    Stlist st=(Stlist) session.get(Stlist.class, stid);
			st.getSt_financelist().add(finance);
			session.save(finance);
			session.save(st);
			ts.commit();
			return true;
		} 
		catch (Exception ex) {
			ex.printStackTrace();
			ts.rollback();
			return false;
		}
		finally {
			if (ts != null) {
				ts = null;
			}
		}
	}
   //查看全部记录
	@Override
	public List<Finance> selectFinance(String stid) {
		Transaction ts = null;
		String hql="";
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			ts = session.beginTransaction();
			hql="from Finance where stid=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, stid);
			List<Finance> list=new ArrayList<Finance>();
			list=query.list();
			ts.commit();
			return list;
		} 
		catch (Exception ex) {
			ex.printStackTrace();
			ts.rollback();
			return null;
		}
		finally {
			if (ts != null) {
				ts = null;
			}
		}
	}
	//查看一条记录
	@Override
	public Finance selectFinancebyId(int finid) {
		Transaction ts = null;
		String hql="";
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			ts = session.beginTransaction();
			hql = "from Finance where fid=?";
			Query query = session.createQuery(hql);
			query.setParameter(0, finid);
			List<Finance> listFinance = query.list();
			ts.commit();
			if(listFinance.get(0)!=null)
			{
				return listFinance.get(0);
			}else
			{
				return null;
			}
			
		} 
		catch (Exception ex) {
			ex.printStackTrace();
			ts.rollback();
			return null;
		}
		finally {
			if (ts != null) {
				ts = null;
			}
		}
	}

}
